from django_redis import get_redis_connection
from rest_framework import serializers

# Serializers
# ModelSerializers : 此处没有优势，因为数据要入库，所以还需要重写create方法
from oauth.models import OAuthQQUser
from apps.users.models import User


class OauthQQSerializer(serializers.Serializer):
    """
    创建QQ关联数据和用户模型数据
    """
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        # 验证用户提交的access_token
        openid = OAuthQQUser.check_openid(attrs.get('access_token'))
        if openid is None:
            raise serializers.ValidationError('授权失败')
        # 把openid添加到attrs中，方便我们在create中获取
        attrs['openid'] = openid

        # 短信验证码
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')

        # 根据手机号查询用户是否存在，如果已经存在，直接绑定这个用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            # 判断用户密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码输入错误')
            # 把user也添加到attrs中，方便我们在create中获取
            attrs['user'] = user

        return attrs

    def create(self, validated_data):
        # 我们需要给
        user = validated_data.get('user')
        if user is None:
            # 如果没有数据，我们根据用户提交的数据创建user
            user = User.objects.create(
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password'),
                username=validated_data.get('username')
            )

            user.set_password(validated_data.get('password'))
            user.save()

        # 再把绑定数据插入到qquser表中
        qquser = OAuthQQUser.objects.create(
            openid=validated_data.get("openid"),
            user=user,
        )

        return user
